package LeetCode.exercise;

import java.util.Stack;

public class LC394 {

    public static void main(String[] args) {
        LC394 l = new LC394();
        String s = l.decodeString("2[abc]3[cd]ef");
        System.out.println(s);
    }
    public String decodeString(String s) {
        Stack<Integer> nums = new Stack<>();
        Stack<String> strs = new Stack<>();
        strs.push("");
        char[] chars = s.toCharArray();
        for(int i = 0; i < s.length(); ){
            if(chars[i] >= '1' && chars[i] <= '9'){
                int num = 0;
                while(i < s.length() && chars[i] >= '1' && chars[i] <= '9'){
                    num = num * 10 + chars[i++] - '0';
                }
                nums.push(num);
                int j = i + 1;
                while(j < s.length() && chars[j] >= 'a' && chars[j] <= 'z'){
                    j++;
                }
                String str = s.substring(i+1, j);
                strs.push(str);
                i = j;
            } else if(chars[i] == ']'){
                int num = nums.pop();
                String res = strs.pop();
                String tmp = "";
                while(num-- > 0){
                    tmp += res;
                }
                strs.push(strs.pop() + tmp);
                i++;
            } else {
                strs.push(strs.pop() + s.substring(i, ++i));
            }
        }
        return strs.pop();
    }
}
